//
//  SJNetRequest.m
//  鼎立华服
//
//  Created by 中企互联 on 2018/1/4.
//  Copyright © 2018年 中企互联. All rights reserved.
//

#import "SJNetRequest.h"
#import <netdb.h>

#define kHttpRequestHeadContentTypeValueMultipart @"multipart/form-data; boundary=forjoritest"
#define kHttpRequestHeadContentTypeKey @"Content-Type"
#define kHttpRequestHeadBoundaryValue @"forjoritest"

static SJNetRequest *httpTool;
static AFHTTPSessionManager * sessionManager;

@implementation SJNetRequest

#pragma mark - Singleton
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        httpTool = [super allocWithZone:zone];
    });
    return httpTool;
}

+ (instancetype)sharedInstance
{
    return [[self alloc] init];
}

- (AFHTTPSessionManager *)getSessionManager{
    
    if(!sessionManager){
        sessionManager = [AFHTTPSessionManager manager];
    }
    //sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 超时时间
    [sessionManager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    //sessionManager.requestSerializer.timeoutInterval = 0.005f;// 模拟超时时间
    sessionManager.requestSerializer.timeoutInterval = kTimeOutInterval;
    [sessionManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    // 支持https
    sessionManager.securityPolicy.allowInvalidCertificates = YES;
    // 最大并发数
    sessionManager.operationQueue.maxConcurrentOperationCount = 3;
    // 配置上传文本格式
    sessionManager.responseSerializer.acceptableContentTypes = [sessionManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    sessionManager.responseSerializer.acceptableContentTypes = [sessionManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"];
    sessionManager.responseSerializer.acceptableContentTypes = [sessionManager.responseSerializer.acceptableContentTypes setByAddingObject:@"multipart/form-data"];
    //
    return sessionManager;
}

+(BOOL)IsConnectToNet
{
    //创建零地址，0.0.0.0的地址表示查询本机的网络连接状态
    struct sockaddr_in zeroAddress;
    
    bzero(&zeroAddress, sizeof(zeroAddress));
    
    zeroAddress.sin_len = sizeof(zeroAddress);
    
    zeroAddress.sin_family = AF_INET;
    
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    
    SCNetworkReachabilityFlags flags;
    
    //获得连接的标志
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    
    CFRelease(defaultRouteReachability);
    //如果不能获取连接标志，则不能连接网络，直接返回
    if (!didRetrieveFlags)
    {
        return NO;
    }
    //根据获得的连接标志进行判断
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    
    return (isReachable && !needsConnection) ? YES : NO;
}



+(void)GETRequest:(NSString *)requestUrl
       WithParams:(NSDictionary *)params
      WithSuccess:(SuccessRequest)success
         WithFail:(FailRequest)fail
     WithNetState:(NetStateIsNo)nonet
{
    if ([self IsConnectToNet] == YES) {
        // 1.获得请求管理者
        AFHTTPSessionManager * sessionManager = [[self sharedInstance] getSessionManager];
        // 2.发送GET请求
        [sessionManager GET:requestUrl parameters:params progress:nil success:^(NSURLSessionDataTask *task, id responseObject){
            
            if (success) {
                success(responseObject);
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error){
            if (fail) {
                fail(error);
            }
        }];
    }else{
        if (nonet) {
            nonet();
        }
    }
}

+(void)POSTRequest:(NSString *)requestUrl
        WithParams:(NSDictionary *)params
       WithSuccess:(SuccessRequest)success
          WithFail:(FailRequest)fail
      WithNetState:(NetStateIsNo)nonet
{
    if ([self IsConnectToNet] == YES) {
        // 1.获得请求管理者
        AFHTTPSessionManager * sessionManager = [[self sharedInstance] getSessionManager];
        // 2.发送POST请求
        [sessionManager POST:requestUrl parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            if (success) {
                success(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (fail) {
                fail(error);
            }
        }];
    }else{
        if (nonet) {
            nonet();
        }
    }
}

+(void)POSTPICRequst:(NSString *)requestUrl
          WithParams:(NSDictionary *)params
       WithImageData:(NSData *)imageData
        WithDataFile:(NSString *)dataFile
       WithImageName:(NSString *)imageName
         WithSuccess:(SuccessRequest)success
            WithFail:(FailRequest)fail
        WithNetState:(NetStateIsNo)nonet
{
    if ([self IsConnectToNet] == YES) {
        // 1.获得请求管理者
        AFHTTPSessionManager *sessionManager = [[self sharedInstance] getSessionManager];
        //
        [sessionManager POST:requestUrl parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData){
            [formData appendPartWithFileData :imageData name:dataFile fileName:[NSString stringWithFormat:@"%@.jpg",imageName] mimeType:@"image/jpeg"];
            
        } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject){
            if (success) {
                success(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
            if (fail) {
                fail(error);
            }
        }];
    }else{
        if (nonet) {
            nonet();
        }
    }
}

@end
